#define  _WIN32_WINNT 0x0500
#include <windows.h>

#include "..\pcommon\pcommon.h"
#include "predator.h"

#define API_VERSION		3

#define EVENT_TIMER		0
#define EVENT_RENDER	1
#define EVENT_OTHER		2

#define long_period		100	/* milliseconds */

static HANDLE g_event[EVENT_OTHER];

/* timer handler */
void Process_Timer(void)
{
	/* signal to rendering event */
	SetEvent(g_event[EVENT_RENDER]);
}

/*
==================
WinMain

==================
*/
HINSTANCE	global_hInstance;
pboolean	really_need_shutdown = true;

int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    MSG				msg;

	/* some parameters given for waitable timer */
	LARGE_INTEGER	next		= { 0, 0 };
	__int64			quad		=-long_period * 10000I64;
	int				timer_period= long_period;

	/* previous instances do not exist in Win32 */
    if (hPrevInstance)
        return 0;

	/* init global instance handle */
	global_hInstance = hInstance;

	/* initialization */
	Pcommon_Init();

	/* create two syncronized objects */
	g_event[EVENT_TIMER]=CreateWaitableTimer(NULL,FALSE,NULL);
	g_event[EVENT_RENDER]=CreateEvent(NULL, FALSE, FALSE, NULL);
	
	/* init the first timer-out time */
	next.QuadPart = quad;

	/* set system timer */
	SetWaitableTimer(g_event[EVENT_TIMER], &next, timer_period, NULL, NULL, FALSE);

    /* main window message loop */
	while (1)
	{
		DWORD result=MsgWaitForMultipleObjects(
			EVENT_OTHER,g_event,FALSE,INFINITE,QS_ALLEVENTS);

		switch (result-WAIT_OBJECT_0) 
		{
			case EVENT_TIMER:
				/* process timer */
				Process_Timer();
				break;

			case EVENT_RENDER:
				/* do rendering */
				Pcommon_Frame();
				break;

			case EVENT_OTHER: 
			{
				while (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) 
				{
					if (msg.message==WM_QUIT) 
					{
						goto _quit;
					}
					else
					{
						TranslateMessage(&msg);
						DispatchMessage(&msg);
					}
				}
				
				break;
			}
		}
	}

_quit:
	/* exit */
	Pcommon_Quit();

	return 0;
}